#include "Warner.h"
#include "Models/WarnMessage.h"

#include <QJsonParseError>
#include <QJsonDocument>
#include <QJsonObject>

Warner::Warner(QObject *parent)
    : QObject{parent}
{
    m_socket = new QTcpSocket();
    connect(m_socket, &QTcpSocket::connected, this, [](){
        qDebug() << "[Warner] TCP连接成功" ;
    });
    connect(m_socket, &QTcpSocket::readyRead, this, [=](){
        QJsonParseError jsonError;
        QJsonDocument doc = QJsonDocument::fromJson(m_socket->readAll(), &jsonError);
        if (jsonError.error != QJsonParseError::NoError)
        {
            qDebug() << "JSON 解析失败：" << jsonError.errorString();
            return;
        }
        if (!doc.isObject())
        {
            qDebug() << "JSON 格式错误：不是对象（可能是数组）";
            return;
        }
        QJsonObject object = doc.object();
        QString device_id = object.value("device_id").toString();
        int data = object.value("data").toInt();
        QString time = object.value("time").toString();

        WarnMessage* temp_message = new WarnMessage(device_id, data, time);
        emit this->warnAccor(temp_message);
    });
    m_socket->connectToHost("127.0.0.1", 5002);

}

Warner &Warner::getInstance()
{
    static Warner instance;
    return instance;
}
